const { observable, action } = require('mobx-miniprogram');
const taskRepository = require('../services/task_repository');
// 使用统一配置入口引用模型
const { TaskModel } = require('../../config/models_config');
const dayjs = require('dayjs');

/**
 * 任务状态管理 Store
 * 使用MobX管理任务状态
 */
export const taskStore = observable({
  // 状态定义
  loading: false,
  error: null,
  tasks: [],
  currentTask: null,
  pagination: { page: 1, size: 20, total: 0, hasMore: true },
  filters: { 
    status: 'all', 
    priority: 'all', 
    assignee: 'all',
    dateRange: null,
    keyword: '',
    tags: []
  },
  currentProjectId: '',
  statistics: {
    pending: 0,
    inProgress: 0,
    completed: 0,
    blocked: 0,
    total: 0,
    completionRate: 0
  },
  selectedTasks: [],
  lastUpdate: null,
  view: 'list', // 'list', 'board', 'calendar', 'gantt'
  sorting: { field: 'updateTime', direction: 'desc' },
  groupBy: null, // null, 'status', 'priority', 'assignee'
  
  // 私有属性
  _refreshTimer: null,
  
  /**
   * 初始化
   */
  init: action(function() {
    console.log('[TaskStore] 初始化');
    this.resetCurrentTask();
    this._setupAutoRefresh();
  }),
  
  /**
   * 获取项目任务列表
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectTasks(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    this.currentProjectId = projectId;
    
    try {
      // 合并筛选参数
      const queryParams = { 
        ...this.filters, 
        ...params,
        page: params.page || this.pagination.page,
        size: params.size || this.pagination.size,
        sort: this.sorting.field,
        order: this.sorting.direction
      };
      
      // 转换状态筛选格式
      if (queryParams.status === 'all') {
        delete queryParams.status;
      }
      
      // 转换优先级筛选格式
      if (queryParams.priority === 'all') {
        delete queryParams.priority;
      }
      
      // 转换负责人筛选格式
      if (queryParams.assignee === 'all') {
        delete queryParams.assignee;
      }
      
      // 调用仓储层
      const result = await taskRepository.getProjectTasks(projectId, queryParams);
      
      // 计算统计数据
      if (result.list) {
        this._calculateStatistics(result.list);
      }
      
      // 批量更新状态
      if (params.page === 1 || !params.page) {
        // 第一页，替换数据
        this.tasks = result.list || [];
      } else {
        // 追加数据，去重
        const newTasks = [...this.tasks];
        (result.list || []).forEach(task => {
          const index = newTasks.findIndex(t => t._id === task._id);
          if (index >= 0) {
            newTasks[index] = task;
          } else {
            newTasks.push(task);
          }
        });
        this.tasks = newTasks;
      }
      
      // 更新分页信息
      this.pagination = {
        page: (result.page || 1) + 1,
        size: result.size || 20,
        total: result.total || 0,
        hasMore: (result.list || []).length === (result.size || 20)
      };
      
      this.loading = false;
      this.lastUpdate = dayjs().format('YYYY-MM-DD HH:mm:ss');
      
      return result;
    } catch (err) {
      this.error = err.message || '获取任务列表失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 加载更多任务
   */
  async loadMoreTasks() {
    if (this.loading || !this.pagination.hasMore) return;
    
    if (!this.currentProjectId) {
      console.warn('[TaskStore] 未设置项目ID，无法加载更多任务');
      return;
    }
    
    return await this.getProjectTasks(this.currentProjectId, {
      page: this.pagination.page
    });
  },
  
  /**
   * 刷新任务列表
   */
  async refreshTasks() {
    if (!this.currentProjectId) {
      console.warn('[TaskStore] 未设置项目ID，无法刷新任务');
      return;
    }
    
    return await this.getProjectTasks(this.currentProjectId, {
      page: 1
    });
  },
  
  /**
   * 获取任务详情
   * @param {String} id 任务ID
   */
  async getTaskDetail(id) {
    if (!id) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 优先从本地查找
      const localTask = this.tasks.find(task => task._id === id);
      if (localTask) {
        this.currentTask = localTask;
        this.loading = false;
        
        // 异步刷新最新数据，但不阻塞UI
        this._asyncRefreshTaskDetail(id);
        
        return localTask;
      }
      
      // 本地没有，调用仓储层
      const task = await taskRepository.getTaskById(id);
      
      // 更新状态
      this.currentTask = task;
      if (task && task.projectId) {
        this.currentProjectId = task.projectId;
      }
      this.loading = false;
      
      return task;
    } catch (err) {
      this.error = err.message || '获取任务详情失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 异步刷新任务详情（不阻塞UI）
   * @param {String} id 任务ID
   */
  async _asyncRefreshTaskDetail(id) {
    try {
      const freshTask = await taskRepository.getTaskById(id);
      
      // 更新当前任务和列表中的任务
      if (this.currentTask && this.currentTask._id === id) {
        this.currentTask = freshTask;
      }
      
      // 更新列表中的任务
      const index = this.tasks.findIndex(task => task._id === id);
      if (index >= 0) {
        this.tasks[index] = freshTask;
      }
    } catch (err) {
      console.error('[TaskStore] 异步刷新任务详情失败:', err);
    }
  },
  
  /**
   * 创建任务
   * @param {Object} taskData 任务数据
   */
  async createTask(taskData) {
    this.loading = true;
    this.error = null;
    
    try {
      // 转换为任务模型
      const task = new TaskModel(taskData);
      
      // 调用仓储层
      const result = await taskRepository.createTask(task);
      
      // 刷新列表
      await this.refreshTasks();
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '创建任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 更新任务
   * @param {Object} taskData 任务数据
   */
  async updateTask(taskData) {
    if (!taskData._id) throw new Error('更新任务时ID不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 转换为任务模型
      const task = new TaskModel(taskData);
      
      // 调用仓储层
      const result = await taskRepository.updateTask(task);
      
      // 更新当前任务
      if (this.currentTask && this.currentTask._id === task._id) {
        this.currentTask = task;
      }
      
      // 更新列表中的任务
      const index = this.tasks.findIndex(t => t._id === task._id);
      if (index >= 0) {
        this.tasks[index] = task;
      }
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '更新任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 更新任务状态
   * @param {String} id 任务ID
   * @param {String} status 新状态
   * @param {String} userId 操作用户ID
   */
  async updateTaskStatus(id, status, userId = '') {
    if (!id) throw new Error('任务ID不能为空');
    if (!status) throw new Error('任务状态不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await taskRepository.updateTaskStatus(id, status, userId);
      
      // 更新当前任务
      if (this.currentTask && this.currentTask._id === id) {
        this.currentTask.status = status;
      }
      
      // 更新列表中的任务
      const index = this.tasks.findIndex(task => task._id === id);
      if (index >= 0) {
        this.tasks[index].status = status;
      }
      
      // 更新统计
      this._calculateStatistics(this.tasks);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '更新任务状态失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 批量更新任务状态
   * @param {Array} ids 任务ID数组
   * @param {String} status 新状态
   */
  async batchUpdateTaskStatus(ids, status) {
    if (!ids || !ids.length) throw new Error('任务ID列表不能为空');
    if (!status) throw new Error('任务状态不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await taskRepository.batchUpdateTaskStatus(ids, status);
      
      // 更新列表中的任务
      ids.forEach(id => {
        const index = this.tasks.findIndex(task => task._id === id);
        if (index >= 0) {
          this.tasks[index].status = status;
        }
        
        // 更新当前任务
        if (this.currentTask && this.currentTask._id === id) {
          this.currentTask.status = status;
        }
      });
      
      // 更新统计
      this._calculateStatistics(this.tasks);
      
      // 清除选中状态
      this.selectedTasks = [];
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '批量更新任务状态失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 删除任务
   * @param {String} id 任务ID
   */
  async deleteTask(id) {
    if (!id) throw new Error('任务ID不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await taskRepository.deleteTask(id);
      
      // 从列表中移除
      this.tasks = this.tasks.filter(task => task._id !== id);
      
      // 清除当前任务
      if (this.currentTask && this.currentTask._id === id) {
        this.currentTask = null;
      }
      
      // 更新统计
      this._calculateStatistics(this.tasks);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '删除任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 批量删除任务
   * @param {Array} ids 任务ID数组
   */
  async batchDeleteTasks(ids) {
    if (!ids || !ids.length) throw new Error('任务ID列表不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await taskRepository.batchDeleteTasks(ids);
      
      // 从列表中移除
      this.tasks = this.tasks.filter(task => !ids.includes(task._id));
      
      // 清除当前任务
      if (this.currentTask && ids.includes(this.currentTask._id)) {
        this.currentTask = null;
      }
      
      // 清除选中状态
      this.selectedTasks = this.selectedTasks.filter(id => !ids.includes(id));
      
      // 更新统计
      this._calculateStatistics(this.tasks);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '批量删除任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 添加任务评论
   * @param {String} taskId 任务ID
   * @param {String} content 评论内容
   * @param {String} userId 用户ID
   * @param {String} userName 用户名称
   */
  async addComment(taskId, content, userId, userName) {
    if (!taskId) throw new Error('任务ID不能为空');
    if (!content) throw new Error('评论内容不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await taskRepository.addComment(taskId, content, userId, userName);
      
      // 刷新任务详情
      await this.getTaskDetail(taskId);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '添加评论失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 添加子任务
   * @param {String} taskId 父任务ID
   * @param {Object} subtaskData 子任务数据
   */
  async addSubtask(taskId, subtaskData) {
    if (!taskId) throw new Error('父任务ID不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 转换为任务模型并设置父任务ID
      const subtask = new TaskModel({ ...subtaskData, parentId: taskId });
      
      // 调用仓储层
      const result = await taskRepository.createTask(subtask);
      
      // 刷新任务详情
      await this.getTaskDetail(taskId);
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '添加子任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 搜索任务
   * @param {String} keyword 搜索关键词
   */
  async searchTasks(keyword) {
    if (!keyword) {
      // 空关键词则恢复原始列表
      this.filters.keyword = '';
      return await this.refreshTasks();
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      // 更新筛选条件
      this.filters.keyword = keyword;
      
      // 执行搜索（实际上是刷新列表，带上新的筛选条件）
      return await this.refreshTasks();
    } catch (err) {
      this.error = err.message || '搜索任务失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 设置筛选条件
   * @param {Object} filters 筛选参数
   */
  setFilters: action(function(filters) {
    this.filters = { ...this.filters, ...filters };
    
    // 重置分页
    this.pagination.page = 1;
    this.pagination.hasMore = true;
  }),
  
  /**
   * 设置排序规则
   * @param {String} field 排序字段
   * @param {String} direction 排序方向
   */
  setSorting: action(function(field, direction) {
    this.sorting = { 
      field: field || 'updateTime', 
      direction: direction || 'desc'
    };
    
    // 重置分页
    this.pagination.page = 1;
    this.pagination.hasMore = true;
  }),
  
  /**
   * 设置分组方式
   * @param {String} groupBy 分组字段
   */
  setGroupBy: action(function(groupBy) {
    this.groupBy = groupBy;
  }),
  
  /**
   * 设置视图类型
   * @param {String} view 视图类型
   */
  setView: action(function(view) {
    this.view = view;
  }),
  
  /**
   * 切换任务选中状态
   * @param {String} taskId 任务ID
   */
  toggleTaskSelection: action(function(taskId) {
    const index = this.selectedTasks.indexOf(taskId);
    if (index >= 0) {
      this.selectedTasks.splice(index, 1);
    } else {
      this.selectedTasks.push(taskId);
    }
  }),
  
  /**
   * 全选/取消全选
   * @param {Boolean} selected 是否选中
   */
  selectAllTasks: action(function(selected) {
    if (selected) {
      this.selectedTasks = this.tasks.map(task => task._id);
    } else {
      this.selectedTasks = [];
    }
  }),
  
  /**
   * 重置当前任务
   */
  resetCurrentTask: action(function() {
    this.currentTask = null;
  }),
  
  /**
   * 设置当前项目ID
   * @param {String} projectId 项目ID
   */
  setCurrentProjectId: action(function(projectId) {
    if (this.currentProjectId !== projectId) {
      this.currentProjectId = projectId;
      
      // 重置状态
      this.tasks = [];
      this.currentTask = null;
      this.pagination.page = 1;
    }
  }),
  
  /**
   * 释放资源
   */
  dispose: action(function() {
    // 清除自动刷新
    this._clearAutoRefresh();
    
    // 清除数据
    this.tasks = [];
    this.currentTask = null;
  }),
  
  /**
   * 计算统计数据
   * @param {Array} tasks 任务列表
   */
  _calculateStatistics(tasks) {
    const stats = {
      pending: 0,
      inProgress: 0,
      completed: 0,
      blocked: 0,
      total: tasks.length,
      completionRate: 0
    };
    
    tasks.forEach(task => {
      if (task.status === 'pending') stats.pending++;
      else if (task.status === 'in_progress') stats.inProgress++;
      else if (task.status === 'completed') stats.completed++;
      else if (task.status === 'blocked') stats.blocked++;
    });
    
    stats.completionRate = stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0;
    
    this.statistics = stats;
  },
  
  /**
   * 设置自动刷新
   */
  _setupAutoRefresh() {
    // 清除现有定时器
    this._clearAutoRefresh();
    
    // 设置新定时器，每5分钟刷新一次
    this._refreshTimer = setInterval(() => {
      if (this.currentProjectId) {
        console.log('[TaskStore] 自动刷新任务列表');
        this.refreshTasks().catch(err => {
          console.error('[TaskStore] 自动刷新失败:', err);
        });
      }
    }, 5 * 60 * 1000);
  },
  
  /**
   * 清除自动刷新
   */
  _clearAutoRefresh() {
    if (this._refreshTimer) {
      clearInterval(this._refreshTimer);
      this._refreshTimer = null;
    }
  }
}); 